package com.tfleo.mealssenger.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import com.github.ignition.core.widgets.RemoteImageView;
import com.tfleo.mealssenger.Main;
import com.tfleo.mealssenger.R;
import com.tfleo.mealssenger.object.FriendSelection;
import com.tfleo.mealssenger.object.Guest;

import android.content.Context;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

public class GuestCheckBoxAdapter extends ArrayAdapter<Guest> {
	private LayoutInflater mInflater;
	private Context mContext;
	private int mHangout;
	private int mMyId;
	private String mAuth;

	public GuestCheckBoxAdapter(Context context, int resource, int textViewResourceId, 
			List<Guest> objects, LayoutInflater inflater, int hangout, int myId, String auth) {
		super(context, resource, textViewResourceId, objects);
		mInflater = inflater;
		mContext = context;
		mHangout = hangout;
		mMyId = myId;
		mAuth = auth;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {   
		ViewHolder holder = null;
		RemoteImageView image = null;
		TextView name = null;
		CheckBox checkBox = null;

		final Guest g = getItem(position);
		final int pos = position;

		if(convertView == null) {
			convertView = mInflater.inflate(R.layout.guest_entry, null);
			holder = new ViewHolder(convertView);
			convertView.setTag(holder);
		}

		holder = (ViewHolder) convertView.getTag();

		name = holder.getNameView();
		name.setText(g.name);

		image = holder.getImageView();
		image.setImageUrl(g.imageUrl);
		image.loadImage();

		checkBox = holder.getCheckboxView();
		checkBox.setChecked(g.getRsvp());
		if(g.id != mMyId) {
			checkBox.setEnabled(false);
		}
		checkBox.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(g.id == mMyId) {
					if(((CheckBox) v).isChecked()) {
						ChangeRsvpTask task = new ChangeRsvpTask();
						task.execute(mHangout, g.id, 1, pos);
					} else {
						ChangeRsvpTask task = new ChangeRsvpTask();
						task.execute(mHangout, g.id, 0, pos);
					}
				}
			}
		});

		return convertView;
	}

	private boolean updateRsvp(int hangout, int guest, int rsvp) {
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(Main.SERVER_URL + "hangout/" + "hangout" + "/rsvp");

		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			//nameValuePairs.add(new BasicNameValuePair("hangout", Integer.toString(hangout)));
			nameValuePairs.add(new BasicNameValuePair("guest", Integer.toString(guest)));
			nameValuePairs.add(new BasicNameValuePair("rsvp", Integer.toString(rsvp)));
			nameValuePairs.add(new BasicNameValuePair("auth", mAuth));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			// Execute HTTP Post Request
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			String responseBody = httpclient.execute(httppost, responseHandler);
			JSONObject response = new JSONObject(responseBody);
			if(response.getInt("code") > 0) {
				return true;
			} else {
				return false;
			}
		} catch(Exception e){
			e.printStackTrace();
		}

		return false;
	}

	private class ViewHolder {
		private View vRow;
		private RemoteImageView vImage = null;
		private TextView vName = null;
		private CheckBox vCheckbox = null;

		public ViewHolder(View row) {
			vRow = row;
		}

		public TextView getNameView() {
			if (vName == null) {
				vName = (TextView) vRow.findViewById(R.id.name);
			}
			return vName;
		}

		public RemoteImageView getImageView() {
			if (vImage == null) {
				vImage = (RemoteImageView) vRow.findViewById(R.id.img);
			}
			return vImage;
		}

		public CheckBox getCheckboxView() {
			if (vCheckbox == null) {
				vCheckbox = (CheckBox) vRow.findViewById(R.id.check);
			}
			return vCheckbox;
		}
	}

	private class ChangeRsvpTask extends AsyncTask<Integer, Void, Boolean> {
		int mPos;
		boolean mRsvp;
		@Override
		protected Boolean doInBackground(Integer... data) {
			mPos = data[3];
			mRsvp = (data[2] == 1);
			return updateRsvp(data[0], data[1], data[2]);
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if(result) {
				getItem(mPos).setRsvp(mRsvp);
			} else {
				getItem(mPos).setRsvp(mRsvp);
				Toast.makeText(mContext, "Error: Server request failed", Toast.LENGTH_SHORT).show();
			}
		}	
	}
}
